<?php
/**
 * Created by PhpStorm.
 * User: huxue
 * Date: 2018/9/11
 * Time: 14:03
 */

class Haimi extends M_Controller
{
    public function index(){
        list($data, $total, $param)	= $this->_limit_page(); // 数据库中分页查询
        $id = (int)$param['id'];
        $this->load->library('dip');
        $this->template->assign(array(
            'list'=>$data,
            'total' => $total,
            'param' => $param,
            'auser' => $this->db->where('id', $id)->get('haimi_paydata')->row_array(),
            'pages'	=> $this->get_pagination(dr_url('admin/haimi/index', array(
                'uid' => $id,
                'total' => $total,
                'search' => IS_POST ? 1 : $this->input->get('search')
            )), $total)
        ));
        $this->template->display('haimi/index.html');
    }



    //关闭订单
    public function close(){
        $oid = $this->input->get_post('oid');
        $order = $this->db->where('id',$oid)->get('haimi_paydata')->row_array();
        if(empty($order)){
            $this->msg("订单不存在");
        }
        if($order['status'] != 0){
            $this->msg("订单在该状态下不能删除");
        }
        $result = $this->db->where('id',$oid)->update('course_order',array('status'=>4));
        if($result){
            $this->admin_msg('关闭订单成功', dr_url(APP_DIR.'/'.$this->router->class.'/index', $this->post_param), 1);
        }

    }

    public function detail(){
        $projectNo = $this->input->get_post('projectNo');
        $data = $this->db->where('projectNo',$projectNo)->get('haimi_paydata')->row_array();
        !$data && exit(fc_lang('对不起，订单数据被删除或者查询不存在'));
        $course = $this->db->where('projectNo',$projectNo)->get('haimi_paydata')->result_array();
        if(empty($course)){
            exit(fc_lang('对不起，课程数据被删除或者查询不存在'));
        }

        $url = 'https://sdk.lovehaimi.com/sdk-web-haimi/merchant/open/auditResult';
        $appId= 'pa6fx3wyyyxz630az6v9k30sp6yb7pr4';
        $secretKey = 'lollzx0xwfy4j8n6n091uhyp7aqjgeupzu8cllascoz4l6tldd7rhd43ak3s586i';
        $str =
            "appId".$appId.
            "projectNo".$projectNo.$secretKey;

        $signvalue=MD5($str);//生成签名
        $arr = array(
            "appId",
            "projectNo",
            "signvalue"
        );

        $arrinfo = compact($arr);
        $arrjson = json_encode($arrinfo);
        $resmsg = $this -> curl_request($arrjson,$url);
//        print_r($resmsg);exit;

        $this->template->assign(array(
                'order'=>$data,
                'course'=>$course,
                'resmsg'=>$resmsg,
                'name'=>'订单详情',
                'totalprice'=>$data['totalprice']
            )
        );
        $this->template->display('haimi/hmorder_detail.html');
    }

    function curl_request($data,$url){
        $curl = curl_init();
        $header = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36','X-AjaxPro-Method:ShowList','Content-Type: application/json', 'Content-Length:' . strlen($data));
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_POST,true);
        curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
        if (!is_null($header)){
            curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
        }
        curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,60);
        curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($curl,CURLOPT_TIMEOUT,10);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        $curl_get = curl_exec($curl);
        curl_close($curl);
        $arrdata=json_decode($curl_get,true);
        $rescode = $arrdata['code'];

        if ($rescode == 30204){
            $resmsg = $arrdata['content']['auditDesc'];
        }else{
            $resmsg = $arrdata['desc'];
        }
        return $resmsg;
    }

    //获取订单状态
    public function orderStatus(){
        $oid  = $this->input->get_post('oid');
        $order = $this->db->select('status')->where('id',$oid)->get('course_order')->row_array();
        $arr = array();
        if(!empty($order)){
            if($order['status']){
                $arr['status'] = 1;
                $arr['msg'] = '订单已经支付成功,3秒后即将跳转';
            }else{
                $arr['status'] = 0;
                $arr['msg'] = '订单未支付';
            }
            echo json_encode($arr);exit;
        }else{
            $arr['status'] = -1;
            $arr['msg'] = '订单不存在';
        }
        echo json_encode($arr);exit;
    }
    //库分期退款
    public function payback(){
        $oid  = $this->input->get_post("oid");
        $order = $this->db->select('order_no,status,mobile')->where('id',$oid)->get('course_order')->row_array();
        if(empty($order)){
            $this->msg("订单不存在获取已经删除");
        }
        //通过手机号码去查下用户
        $user = $this->db->select('id')->where('mobile',$order['mobile'])->get('user')->row_array();
        $data = array(
            "orderId"=>$order['order_no'],
            "applyId"=>'47521',
            "refundAmount"=>600,
            "reson"=>'错误转款',
        );
        $risk = array(
            "deviceType"=>equipType('pc'),
            'ip'=> $_SERVER['REMOTE_ADDR'],
        );
        $param = array(
            "uid"=>$user['id'],
            "midTransaction"=>midPlatform,
            "opType"=>3001,
            "time"=>microtime(true)*1000,
            "data"=>$data,
            "risk"=>$risk
        );

        $json = json_encode($param);
        $this->load->library("secooCrypt");
        $encryptObj = new SecooCrypt();
        $result = $encryptObj->requestEncrypt(AEC_KEY,MD5_KEY,midPlatform,VERSION,$json);//加密结果
        $res = cur_post(KU_FENG_QI_URL,$result);
        $obj = json_decode($res,true);;
        $resultJson = "{\"sign\":\"".$obj['sign']."\",\"data\":\"".$obj['data']."\"}";
        $m = $encryptObj->responseDecrypt(AEC_KEY,MD5_KEY,$resultJson);//解密结果
        $resObj = json_decode($m,true);
        if($resObj['result'] == 200){
            $this->msg("退款成功");
        }else{
            $this->msg('退款失败');
        }
    }
//    //修改订单状态
//    public function modifyOrderStatus(){
//        $sign = $this->input->get_post('sign');
//        $order_no = $this->input->get_post('order_no');
//        $pay_type = $this->input->get_post('pay_type');
//        if(!empty($sign) && $sign == 'SD45645sdfmlsdfjusd12132snxnzchaqllqaqwqweqewq45dvs'){
//            $paytype = 0;
//            if($pay_type == 'zfb'){
//                $paytype = 1;
//            }else if($pay_type == 'wx'){
//                $paytype = 2;
//            }
//            $this->db->where('order_no',$order_no)->update('course_order',array('pay_type'=>$paytype,'status'=>1));
//        }
//    }

    private function _where(&$select) {

        $uid = (int)$this->input->get('id');
        $uid = $uid ? $uid : $this->uid;
        $search = $this->input->get('search');
        $cache_file = md5($this->duri->uri(1).$uid.$this->uid.SITE_ID.$this->input->ip_address().$this->input->user_agent()); // 缓存文件名称
        // 存在POST提交时，重新生成缓存文件
        if (IS_POST) {
            $data = $this->input->post('data');
            $this->cache->file->save($cache_file, $data, 3600);
            $search = 1;
            unset($_GET['page']);
        }
//        $select->where('id', $uid);
//        $select->where('is_del', 1);
        // 存在search参数时，读取缓存文件
        if ($search == 1) {
            $data = $this->cache->file->get($cache_file);
            if (isset($data['start']) && $data['start'] && $data['start'] != $data['end']) {
                $data['end'] = $data['end'] ? $data['end'] : SYS_TIME;
                $select->where('logintime BETWEEN '.$data['start'].' AND '. $data['end']);
            }
        }
        $data['id'] = $uid;
        return $data;
    }

    private function  _limit_page(){
        $page = max((int)$this->input->get_post('page'),1);
        $_total = (int)$this->input->get_post('total');

        if(!$_total){
//            $_total = $this->db->count_all_results('course_order');
            $count = $this->db->select("count(*) as count")->get('haimi_paydata')->row_array();
            $_total = $count['count'];
//            if(!$_total){
////                return array(array(), 0 ,$_param);
//                return array();
//            }
        }

        $select = $this->db;
        $_param = $this->_where($select);
        $result = $this->db
            ->limit(SITE_ADMIN_PAGESIZE, SITE_ADMIN_PAGESIZE * ($page - 1))
            ->order_by('id desc')
            ->get('haimi_paydata')
            ->result_array();
        return array($result,$_total, $_param);
    }



}